<template>
  <div class="login-account">
    <el-form label-width="auto" :rules="rules" ref="formRef" :model="account">
      <el-form-item label="用户" prop="username" class="p-t-10">
        <el-input v-model="account.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" class="p-t-10">
        <el-input v-model="account.password" type="password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { FormRules } from 'element-plus/lib/tokens/form'
import { defineComponent, reactive, ref } from 'vue'
import { ElForm } from 'element-plus'
import LocalCache from '@/utils/cache'
import { useStore } from 'vuex'

export default defineComponent({
  setup() {
    const account = reactive({
      username: LocalCache.getItem('username') ?? '',
      password: LocalCache.getItem('password') ?? ''
    })
    const store = useStore()
    const formRef = ref<InstanceType<typeof ElForm>>()
    function handleLoginClick(isKeepPassword: boolean) {
      // 验证表单是否成功
      formRef.value?.validate(async (isValid) => {
        if (isValid) {
          // 调用 action 发送登录请求 存储到 Vuex 中
          store.dispatch('LoginModule/AccountLoginActions', { ...account })
          // 记住密码
          if (isKeepPassword) {
            // 存在本地
            LocalCache.setItem('username', account.username)
            LocalCache.setItem('password', account.password)
          } else {
            LocalCache.clear()
          }
        }
      })
    }
    const rules: FormRules = {
      username: [
        {
          required: true,
          message: 'Username must not be empty',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: 'Length should be 3 to 10',
          trigger: 'blur'
        }
      ],
      password: [
        {
          required: true,
          message: 'Password must not be empty',
          trigger: 'blur'
        },
        { min: 6, message: 'Length should be min 6', trigger: 'blur' }
      ]
    }
    return { handleLoginClick, rules, account, formRef }
  }
})
</script>

<style scoped lang="less">
.login-account {
  width: 100%;
  height: 100%;
  .p-t-10 {
    padding-top: 10px;
  }
}
</style>
